/*
 * @Author: wuzhen
 * @Date: 2020-01-16 15:35:57
 * @LastEditors  : wuzhen
 * @LastEditTime : 2020-01-16 15:41:44
 * @Description:公用方法
 */
import pinyin from "pinyin";
// 中文转首字母英文
export const formatLetter = str => {
  const letter = pinyin(str)[0][0]
    .slice(0, 1)
    .toUpperCase();
  return letter;
};

// 判断文件类型
export const formatFileType = fileName => {
  const arry = fileName.split('.');
  // .后缀
  const type = arry[arry.length - 1];
  if (type === 'png' || type === 'jpg' || type==="gif") {
    return "image";
  } else if (type === 'xls' || type === "xlsx") {
    return "xls";
  } else if (type === 'docx' || type === 'doc') {
    return "doc";
  } else if (type === 'txt' || type === 'rtf') {
    return "txt";
  } else if (type === 'ppt' || type === "pptx") {
    return "ppt";
  } else if (type === 'ppt' || type === "pptx") {
    return "ppt";
  } else if (type === 'pdf') {
    return "pdf";
  } else if (type === 'html') {
    return "html";
  } else if (type === 'zip') {
    return "zip";
  } else if (type === "rar") {
    return "rar";
  } else if (type === 'mp3') {
    return "music";
  } else if (type === 'mp4' || type ==="wmv") {
    return "mov";
  } else {
    return "default";
  }
};

// file文件转base64
export const imageToBase64 = file => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => {
    console.log('file 转 base64结果：' + reader.result);
  };
};

// 文件大小单位转换Bytes、KB、MB、GB
export const renderSize = filesize => {
  if (filesize === null || filesize === '' || !filesize){
    return "0 B";
  }
  const unitArr = ["B","KB","MB","GB","TB","PB","EB","ZB","YB"];
  let index = 0;
  const srcsize = parseFloat(filesize);
  index=Math.floor(Math.log(srcsize)/Math.log(1024));
  let size =srcsize/Math.pow(1024,index);
  size=size.toFixed(2);//保留的小数位数
  return size+unitArr[index];
};